package com.person.controller;

import cn.hutool.core.util.IdUtil;
import com.person.common.R;
import com.person.dto.UserDto;
import com.person.pojo.User;
import com.person.service.UserService;
import com.person.utils.SMSUtils;
import com.person.utils.ValidateCodeUtils;
import io.netty.util.internal.StringUtil;
import org.apache.http.protocol.HttpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.events.Event;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    /**
     * 短信验证码登录
     */



    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.hasLength(phone)){
            //生成4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("短信验证码：{}",code);
            //调用阿里云api，完成发送短信
           // SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
            //将验证码保存到session中
            session.setAttribute(phone,code);
            return R.success("发送成功");
        }
        return R.error("发送失败");

    }

    /**
     * 用户登录
     * @param userDto
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody UserDto userDto, HttpSession session){
        log.info("{}",userDto);
        //获取手机号
        String phone = userDto.getPhone();

        //获取前端填写的验证码
        String code = userDto.getCode();
        //获取session中保存的验证码
        String codeInSession =(String) session.getAttribute(phone);

        //将session和前端中的验证码进行比对
        if (codeInSession!=null && codeInSession.equals(code)){
            //如果成立说明，登录成功
            //判断用户是否是新用户，如果是自动注册
            User user = userService.inquireTEL(phone);
            if (user==null){
                //自动注册
                Long id = IdUtil.getSnowflakeNextId();
                userDto.setId(id);
                userService.addUser(userDto);
                user = new User();
                user.setId(id);
                user.setPhone(phone);

            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登陆失败");

    }


}
